// 导入生成Token的包
const jwt = require("jsonwebtoken");
// const { createCanvas, loadImage } = require("canvas");
const ossClient = require("../oss/index");
const fs = require("fs");
const path = require("path");
const Jimp = require("jimp");
const dayjs = require("dayjs");
const multiparty = require("multiparty");
// 自定义请求头
const headers = {
  // 指定Object的存储类型。
  "x-oss-storage-class": "Standard",
  // 指定Object的访问权限。
  "x-oss-object-acl": "private",
  // 通过文件URL访问文件时，指定以附件形式下载文件，下载后的文件名称定义为example.txt。
  "Content-Disposition": 'attachment; filename="example.txt"',
  // 设置Object的标签，可同时设置多个标签。
  "x-oss-tagging": "Tag1=1&Tag2=2",
  // 指定PutObject操作时是否覆盖同名目标Object。此处设置为true，表示禁止覆盖同名Object。
  "x-oss-forbid-overwrite": "true",
};
// 登录处理函数
exports.login = async (req, res) => {
  // 接受表单的数据
  const userinfo = req.body;
  if (!userinfo.email) {
    return res.cc("请输入邮箱！");
  }

  // 定义SQL语句
  const sql = `select * from fa_users where email=?`;
  //  执行SQL语句，根据email查询用户的信息
  global.query(sql, userinfo.email).then((results) => {
    //  执行SQL语句成功，但是获取到的数据条数不等于1
    if (results.length !== 1) return res.cc("登录失败");
    //  在服务器端生成token的字符串
    const user = {
      id: results[0].id,
      team_id: results[0].team_id,
    };
    // 对用户信息进行加密，生成token字符串
    const tokenStr = jwt.sign(user, process.env.SECRET_KEY, {
      expiresIn: process.env.EXPIRESIN,
    });
    global.connectRedis.set(results[0].id, tokenStr, "EX", 24 * 100 * 60 * 60);
    // 调用res.send()将token响应给客户端
    const update_sql = `update fa_users set is_login = ? where id = ?`;
    global.query(update_sql, [1, user.id]);
    res.send({
      code: 200,
      msg: "登录成功",
      token: "Bearer " + tokenStr,
    });
  });
};
// 获取团队code
exports.getCode = async (req, res) => {
  const { id, team_id } = req.user;
  if (id !== undefined && team_id !== undefined) {
    const sql = "SELECT code FROM fa_users WHERE id=? AND team_id=?";
    const result = await global.query(sql, [id, team_id]);
    if (result.length > 0) {
      res.send({ code: 200, msg: "success", data: result });
    } else {
      res.cc("暂无用户信息,生成code失败");
    }
  } else {
    res.cc("请填写正确的用户ID");
  }
};
async function createPoster(req, res, code) {
  const { id, team_id } = req.user;
  const imageSrc = path.join(__dirname, "../public/images/bg.png");
  console.log("imageSrc---", imageSrc);
  // 图片文件路径数组
  const imagePaths = [
    path.join(__dirname, "../public/images/1.png"),
    path.join(__dirname, "../public/images/2.png"),
    path.join(__dirname, "../public/images/3.png"),
    path.join(__dirname, "../public/images/4.png"),
    path.join(__dirname, "../public/images/5.png"),
  ];
  // 设置画布尺寸，根据图片尺寸和布局调整
  const canvasWidth = 995;
  const canvasHeight = 1722;
  // 创建画布
  const canvas = createCanvas(canvasWidth, canvasHeight);
  const ctx = canvas.getContext("2d");
  // 加载背景图片
  const background = await Jimp.read(imageSrc);
  background.resize(canvasWidth, canvasHeight);
  const buffer = await background.getBufferAsync(Jimp.MIME_PNG);
  const img = await loadImage(buffer);
  // 小图片位置
  let x = 0;
  let y = 0;
  let imgWidth = 130; // 假定每个图片的显示宽度
  let imgHeight = 131; // 假定每个图片的显示高度
  const codeArr = Array.from(code);
  codeArr.map((item) => {
    imagePaths.map(async (imgPath, index) => {
      if (item - 1 == index) {
        const image = await loadImage(imgPath);
        if (codeArr[0] - 1 == index) {
          x += imgWidth + 3; // 图片间的间距，可调整
        } else {
          x += imgWidth + 20; // 图片间的间距，可调整
        }
        y = imgHeight - 3;
        console.log("x--y", x, y);
        ctx.drawImage(image, x, y, imgWidth, imgHeight);
        // 如果达到行末，换行
        if (x + imgWidth > canvasWidth) {
          x = 0;
          y += imgHeight + 20; // 行间距，可调整
        }
      }
    });
  });

  // 绘制图片
  ctx.drawImage(img, 0, 0);
  // // 设置文字样式
  // ctx.font = "40px sans-serif";
  // ctx.fillStyle = "white";
  // ctx.textAlign = "center";
  // ctx.textBaseline = "middle";
  // // 计算文字位置
  // const textWidth = ctx.measureText(text).width;
  // const x = canvas.width / 2 - textWidth / 2 + 230;
  // const y = canvas.height / 2;
  // 绘制文字
  // ctx.fillText(text, x, y);

  // 输出图片
  // const out = fs.createWriteStream(
  //   path.join(__dirname, "../public/images/output.png")
  // );
  const create_time = dayjs().format("YYYYMMDDHHmmss");
  const stream = canvas.createPNGStream();
  // stream.pipe(out);
  console.log("海报生成完毕");
  // res.cc("海报生成完毕", 200);
  const sql = `SELECT * FROM fa_team WHERE team_id=? LIMIT 1`;
  global.query(sql, [team_id]).then(async (sqlResults) => {
    if (sqlResults.length > 0) {
      const share_img = sqlResults[0]["share_img"];
      if (share_img != "") {
        res.send({
          code: 200,
          msg: "success",
          data: share_img,
        });
      } else {
        const fileName = "poster-" + create_time + ".jpg";
        const result = await ossClient.putStream(
          "dev/" + fileName + "",
          stream
        );
        console.log("result--", result);
        const updated_time = dayjs().format("YYYY-MM-DD HH:mm:ss");
        const sql_up = `UPDATE fa_team SET share_img = ? , updated_time = ? WHERE team_id = ?`;
        await global
          .query(sql_up, [result.url, updated_time, team_id])
          .then(async (sqlResults) => {
            console.log("sqlResults", sqlResults);
          });
        res.send({ code: 200, msg: "success", data: result.url });
      }
    }
  });
}
// 获取海报
exports.getPlacard = async (req, res) => {
  // 使用函数生成海报  生成海报根据用户是哪个队伍的第一个用户，生成一张海报保存到数据库中
  const { code } = req.query;
  // await createPoster(req, res, code).catch((err) => console.error(err));
};
// 修改用户头像
exports.updateAvatar = async (req, res) => {
  const { id } = req.user;
  const { avatar_url } = req.query;
  const sql = `SELECT * from  fa_users WHERE id=?`;
  global.query(sql, [id]).then(async (sqlResults) => {
    if (sqlResults.length > 0) {
      const update_time = dayjs().format("YYYY-MM-DD HH:mm:ss");
      const updateAvatarSql = `UPDATE fa_users SET avatar_url = ? , update_time = ?  WHERE id = ? `;
      global
        .query(updateAvatarSql, [avatar_url, update_time, id])
        .then((results) => {
          if (results.affectedRows != 1) {
            return res.cc("上传头像失败");
          } else {
            res.send({ code: 200, msg: "success", avatar_url: avatar_url });
          }
        });
    } else {
      return res.cc("暂无用户信息");
    }
  });
};
// 修改用户头像（备选）
exports.updateAvatarCopy = async (req, res) => {
  const form = new multiparty.Form();
  form.parse(req, async (err, fields, files) => {
    const { user_id } = fields;
    if (err) {
      return res.cc(err.message);
    }
    const sql = `SELECT * from  fa_users WHERE id=?`;
    global.query(sql, [user_id]).then(async (sqlResults) => {
      if (sqlResults.length > 0) {
        // const fileName = files.image[0].originalFilename;
        const fileUrl = files.avatar[0].path;
        const fileUrlArr = files.avatar[0].path.split("/");
        const fileName = fileUrlArr.pop();
        console.log(fileName);
        const reg = /(\.jpg|\.jpeg|\.JPG|\.JPEG|\.PNG|\.png)$/g;
        if (!reg.test(fileName)) {
          return res.cc("请上传正确的图片jpg|jpeg|png格式");
        }
        const result = await ossClient.put(
          "dev/" + fileName + "",
          path.normalize(fileUrl),
          { headers }
        );
        const avatar_url = result.url;
        const update_time = dayjs().format("YYYY-MM-DD HH:mm:ss");
        const updateAvatarSql = `UPDATE fa_users SET avatar_url = ?,update_time = ?  WHERE id = ? `;
        global
          .query(updateAvatarSql, [avatar_url, update_time, user_id])
          .then((results) => {
            if (results.affectedRows != 1) {
              return res.cc("上传头像失败");
            } else {
              res.send({ code: 200, msg: "success", data: avatar_url });
            }
          });
      } else {
        return res.cc("暂无用户信息");
      }
    });
  });
};
//获取用户信息列表
exports.getUsersList = async (req, res) => {
  const sql = `SELECT * FROM fa_users`;
  global.query(sql).then((sqlResults) => {
    if (sqlResults.length > 0) {
      res.send({ code: 200, msg: "success", data: sqlResults });
    } else {
      return res.cc("暂无用户信息");
    }
  });
};
// 获取用户信息
exports.getUserInfo = async (req, res) => {
  const { id, team_id } = req.user;
  let resultArr = {};
  let resultLikeArr = {};
  const sql_0 = `SELECT score from fa_rank WHERE user_id = ?`;
  const sqlScoreRes = await global.query(sql_0, [id, team_id]);
  if (sqlScoreRes.length > 0) {
    resultArr = { score: sqlScoreRes[0].score };
  } else {
    resultArr = { score: 0 };
  }
  const sql_1 = `SELECT likes from fa_images WHERE user_id = ? AND type = 2`;
  const sqlLikesRes = await global.query(sql_1, [id, team_id]);
  if (sqlLikesRes.length > 0) {
    resultLikeArr = { likes: sqlLikesRes[0].likes };
  } else {
    resultLikeArr = { likes: 0 };
  }
  const sql = `SELECT * FROM fa_users WHERE id = ? AND team_id = ?`;
  global.query(sql, [id, team_id]).then((sqlResults) => {
    if (sqlResults.length > 0) {
      res.send({
        code: 200,
        msg: "success",
        data: { ...sqlResults[0], ...resultArr, ...resultLikeArr },
      });
    } else {
      return res.cc("获取用户信息失败！");
    }
  });
};
// 获取点赞数和分数
exports.myInfo = (req, res) => {
  const { id, team_id } = req.user;
  const sql = `SELECT * FROM fa_images WHERE id = ? AND team_id = ?`;
};
